<?php

namespace wchat\wx\V3;

use Exception;
use JetBrains\PhpStorm\ArrayShape;
use Kiri;
use wchat\wx\SmallProgram;
use wchat\wx\V3\Libs\TransferDetail;

class WxV3Transfer extends SmallProgram
{
    use WxV3PaymentTait;

    /**
     * @param TransferDetail $detail
     * @return array<'out_bill_no', 'transfer_bill_no', 'create_time', 'state'>
     * @throws Exception
     */
    #[ArrayShape([])]
    public function transfer(TransferDetail $detail): array
    {
        $payConfig = $this->getPayConfig();
        $body      = $detail->toArray();
        if ($payConfig->typeIsApp()) {
            $body['appid'] = $payConfig->pay->wx->appId;
        } else {
            $body['appid'] = $payConfig->appId;
        }
        $sign = $this->signature('POST', '/v3/fund-app/mch-transfer/transfer-bills', $json = json_encode($body, JSON_UNESCAPED_UNICODE));

        $client = $this->createClient($sign, $json);
        $client->post('/v3/fund-app/mch-transfer/transfer-bills');
        $client->close();

        Kiri::getLogger()->println($client->getBody());

        if ($client->getStatusCode() == 200) {
            return json_decode($client->getBody(), TRUE);
        }
        throw new Exception('转账申请发起失败');
    }


}
